﻿using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using Dapper;
using Newtonsoft.Json;
using NLog;
using Oracle.ManagedDataAccess.Client;

namespace Raise.Workbench.Tools {
    public static class DapperDbContext {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger(typeof(DapperDbContext));

        private static IDbConnection GetConnection {
            get {
                string connString = Utils.GetConnectString();
                return new OracleConnection(connString);
            }
        }

        public static List<T> AsList<T>(this IEnumerable<T> source) {
            if(source != null && !(source is List<T>))
                return source.ToList();
            return (List<T>)source;
        }

        public static int Execute(string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null, int databaseOption = 1) {
            using(var conn = GetConnection) {
                var info = "SQL语句:" + sql + "  \n SQL参数: " + JsonConvert.SerializeObject(param) + " \n";
                var sw = new Stopwatch();
                sw.Start();
                var restult = conn.Execute(sql, param, transaction, commandTimeout, commandType);
                sw.Stop();
                Logger.Info(info + "耗时:" + sw.ElapsedMilliseconds + (sw.ElapsedMilliseconds > 1000 ? "#####" : string.Empty) + "\n");
                return restult;
            }
        }

        public static int Execute(CommandDefinition command, int databaseOption = 1) {
            using(var conn = GetConnection) {
                var info = " SQL语句:" + command.CommandText + "  \n SQL命令类型: " + command.CommandType + " \n";
                var sw = new Stopwatch(); sw.Start();
                var restult = conn.Execute(command);
                sw.Stop();
                Logger.Info(info + "耗时:" + sw.ElapsedMilliseconds + (sw.ElapsedMilliseconds > 1000 ? "#####" : string.Empty) + "\n");
                return restult;
            }
        }
    }
}
